package com.qumitech.visualnovel.component.util.bash;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * //                       _oo0oo_
 * //                      o8888888o
 * //                      88" . "88
 * //                      (| -_- |)
 * //                      0\  =  /0
 * //                    ___/`---'\___
 * //                  .' \\|     |// '.
 * //                 / \\|||  :  |||// \
 * //                / _||||| -:- |||||- \
 * //               |   | \\\  -  /// |   |
 * //               | \_|  ''\---/''  |_/ |
 * //               \  .-\__  '-'  ___/-. /
 * //             ___'. .'  /--.--\  `. .'___
 * //          ."" '<  `.___\_<|>_/___.' >' "".
 * //         | | :  `- \`.;`\ _ /`;.`/ - ` : | |
 * //         \  \ `_.   \_ __\ /__ _/   .-` /  /
 * //     =====`-.____`.___ \_____/___.-`___.-'=====
 * //                       `=---='
 * //
 * //
 * //     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 * //
 * //               佛祖保佑         永无BUG
 * <p>
 * com.qumitech.visualnovel.component.util.bash
 * Created on 2020/9/8.
 */
public class FileUtils {


    public static int fileLength(String file) {
        try {
            Process builder = new ProcessBuilder().command(
                    "wc","-l", file
            ).start();
            builder.waitFor();
            List<String> lines = ResultUtil.getResult(builder);
            if (lines.size() > 0) {
                String split = lines.get(0).trim().split("\\s+")[0];
                return Integer.parseInt(split);
            }
        } catch (IOException | InterruptedException e) {
        }
        return 0;
    }

    public static List<String> readOffsetLimit(String file, int offset, int limit) {
        List<String> result = Collections.emptyList();
        try {
            Process process = new ProcessBuilder().command(
                    "sed","-n", String.format("%d,%dp", offset + 1, offset + limit), file
//                    "sed","-n","1,4p",file
            ).redirectErrorStream(true).start();
            process.waitFor();
            result = ResultUtil.getResult(process);
            return result;
        } catch (IOException | InterruptedException e) {
        }
        return result;
    }



    public static void main(String[] args) {
//        System.out.println(fileLength("/Users/danliu/code/company_2/hiya/data_analysis/jobs/account_direct_seeding_2020-09-07_2020-09-07_2020-09-08-11-09.csv"));
        String file = "/Users/danliu/code/company_2/hiya/data_analysis/jobs/account_direct_seeding_2020-09-07_2020-09-07_2020-09-08-11-09.csv";
        int count = fileLength(file);
        System.out.println(count);
        List<String> offset = readOffsetLimit(file, 1, 3);
        offset.forEach(System.out::println);
    }

}
